package com.oa.role.dto;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

import com.oa.system.entity.Role;
import com.oa.system.entity.UserInfo;

public class RoleDto {
	private Long id; // userID
	private String fullname;
	private String dept;
	private String job;
	private String role;
	private Long roleId;

	public Long getId() {
		return id;
	}

	public String getFullname() {
		return fullname;
	}

	public String getDept() {
		return dept;
	}

	public String getJob() {
		return job;
	}

	public String getRole() {
		return role;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setFullname(String fullname) {
		this.fullname = fullname;
	}

	public void setDept(String dept) {
		this.dept = dept;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	public static RoleDto toRoleDto(UserInfo userInfo) {
		RoleDto roleDto = new RoleDto();
		roleDto.setId(userInfo.getId());
		roleDto.setFullname(userInfo.getFullname());
		roleDto.setJob(userInfo.getJob());

		if (userInfo.getDept() != null) {
			roleDto.setDept(userInfo.getDept().getName());
		}

		if (userInfo.getRole() != null) {
			roleDto.setRole(userInfo.getRole().getRole());
			roleDto.setRoleId(userInfo.getRole().getId());
		}

		return roleDto;
	}

	public static Specification<Role> getRoleGroupQuery(RoleDto roleDto) {
		return new Specification<Role>() {

			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<>();
				if (roleDto.getRole() != null && roleDto.getRole().trim().length() > 0) {
					Predicate predicate = cb.like(root.get("role").as(String.class), "%" + roleDto.getRole() + "%");
					list.add(predicate);
				}

				Predicate[] predicates = new Predicate[list.size()];
				return cb.and(list.toArray(predicates));
			}

		};
	}

}
